package query;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import gui.Main;

public class QueryGenerationManager {
	
	
	private static ArrayList<String> questionList = new ArrayList<String>();
	private static ArrayList<ArrayList<Query>> queryPerQuestionList = new ArrayList<ArrayList<Query>>();

	public static void queryManagement () {
		
		int i;
		/*
		 * 1. Analiazar Pregunta
		 * 2. Crear Query
		 */
		
		//Coger Preguntas
		if (Main.getFile() != null) {
			//DESDE FICHERO
			System.out.println("Adding questions from file");
			addQuestionsFromFile(Main.getFile());
		} else if (!Main.getQuestion().equals("")) {
			//DESDE CUADRO DE TEXTO
			System.out.println("Adding questions from gui");
			addQuestion(Main.getQuestion());
		} else if (questionList.isEmpty()) {
			//Si no ha habido preguntas en fichero ni cuadro de texto, usa una de ejemplo
			System.out.println("NO GIVEN QUESTIONS");
			addQuestion("0001	What calculating aid was invented by William Oughtred in 1662?");
		}
		
		//Generacion de la query de cada pregunta
		for (i = 0; i < questionList.size(); i++) {
			queryPerQuestionList.add(new ArrayList<Query>());
			addQuery(new Query(QuestionAnalyzer.analyzeQuestion(questionList.get(i))),i);
		}
		
		//Imprime cada query string, para comprobar errores
		for (int g = 0; g < queryPerQuestionList.size(); g++) {
			for (i = 0; i < queryPerQuestionList.get(g).size(); i++) {
				System.out.println(queryPerQuestionList.get(g).get(i).getQueryString());
			}
		}
		
		//QUITAR ESTE SYSTEM EXIT PARA CONECTAR CON EL RESTO DE LAS PARTES
				//System.exit(0);
				Main.printText("Query generada...");
	}
	
	private static void addQuestionsFromFile(File questionsFile) {
		try {
			BufferedReader in = new BufferedReader(new FileReader(questionsFile));
			String line;
			
			while ((line = in.readLine()) != null)  {
				line = line.trim();
				
				// add whole word
				if (line.length() > 0){
					addQuestion(line);
				}
			}
	
			in.close();
		}
		catch (IOException e) {
			e.printStackTrace();
			System.out.println("WAT");
		}
		
	}

	public static ArrayList<String> getQuestionList() {
		return questionList;
	}

	public static void addQuestion(String question) {
		questionList.add(question);
	}

	public static ArrayList<ArrayList<Query>> getQueryList() {
		return queryPerQuestionList;
	}

	public static void addQuery(Query query, int i) {
		//Cada posicion i representa a una pregunta, que puede tener n queries
		if(queryPerQuestionList.get(i)==null){
			queryPerQuestionList.set(i, new ArrayList<Query>());
		}
		queryPerQuestionList.get(i).add(query);
	}
	
}
